package com.dataaccess.dataaccess.support.aibox;

import cn.hutool.json.JSONObject;
import com.dataaccess.dataaccess.common.utils.appkit.ConfigKit;
import com.dataaccess.dataaccess.support.utils.X509TrustUtiil;
import com.dataaccess.dataaccess.web.service.VisualizationVideoAlarmService;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;


import javax.annotation.Resource;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Component
public class PictureDownload {
    @Resource
    VisualizationVideoAlarmService visualizationVideoAlarmService;
    public static void main(String[] args) throws Exception {
        String url = "https://iotx-vision-picture-citylink-ca16.oss-accelerate.aliyuncs.com/DjxFYQsugdOCcCrecrG7NNE_wrV7ztI55e82wBthSlM/081f486e50e24b898dbb5c41470969ba?Expires=1601184790&OSSAccessKeyId=LTAI4FpWA53sEvZgar6Q7McQ&Signature=zpGc9XxpjmrI3pfG3lvG5%2BjXk8k%3D";
        downloadFile(url);
    }
    //链接url下载图片
    public void downloadPicture(JSONObject jsonObject) throws Exception {
        //报警图片的信息
        JSONObject alarmPicUrl = jsonObject.getJSONObject("AlarmPicUrl");
        JSONObject data = alarmPicUrl.getJSONObject("data");
        JSONObject Data = data.getJSONObject("Data");
        String picUrl = Data.getStr("PicUrl");
        URL url = null;
        int imageNumber = 0;

        try {
            url = new URL(picUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String fileName =  System.currentTimeMillis() + ".jpg";
            String imageName = ConfigKit.getStr("fileSavePath","upload")+"/aiBoxImg/"+fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context=output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            String filePath = ConfigKit.getStr("webPath","upload")+"aiBoxImg/"+fileName;
            jsonObject.put("AlarmPicPath",filePath);
            visualizationVideoAlarmService.aiBox(jsonObject);
            System.out.println("++++AlarmPicPath+++++++:"+filePath);
            System.out.println("++++最终json串+++++++:"+jsonObject.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //链接url下载图片
    public static String downloadPicture(String picUrl) throws Exception {

        URL url = null;
        int imageNumber = 0;

        try {
            url = new URL(picUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String fileName =  System.currentTimeMillis() + ".jpg";
            String imageName = ConfigKit.getStr("fileSavePath","upload")+"/aiBoxImg/"+fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context=output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            String filePath = ConfigKit.getStr("webPath","upload")+"aiBoxImg/"+fileName;
            return filePath;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String downloadFile(String fileUrl) throws Exception {
        String fileName = System.currentTimeMillis() + ".jpg";
        SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
        sslcontext.init(null, new TrustManager[] { new X509TrustUtiil() }, new java.security.SecureRandom());
        URL url = new URL(fileUrl);
        HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslsession) {
                System.out.println("WARNING: Hostname is not matched for cert.");
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
        HttpsURLConnection urlCon = (HttpsURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        // 读文件流
        String imgUrl = ConfigKit.getStr("webPath", "upload") + "aiBoxImg/" + fileName;
        String imageName = ConfigKit.getStr("fileSavePath", "upload") + "/aiBoxImg/" + fileName;
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(imageName));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        out.close();
        in.close();
        return imgUrl;
    }

    /**
     * @Author YangYu
     * @Description base64图片转io并输出
     * @Date Created in 10:37 2021/11/17
     * @Param [strBase64]
     */

    public static String base64ToIo(String strBase64,String folderName) throws IOException {
        //生成的新文件
        String fileName = System.currentTimeMillis() + ".jpg";
        // 读文件流
        String imgUrl = ConfigKit.getStr("webPath", "upload")+folderName+"/images/"+ fileName;
        String imageName = ConfigKit.getStr("fileSavePath", "upload") + "/"+folderName+"/images/"+ fileName;
        //String imageName = "e:/"+folderName+"/images/"+ fileName;
        try {
            // 解码，然后将字节转换为文件
            //将字符串转换为byte数组
            byte[] bytes = new BASE64Decoder().decodeBuffer(strBase64);
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            FileOutputStream out = new FileOutputStream(imageName);
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread); //文件写操作
            }
            out.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return imgUrl;
    }
}
